/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components.panels;

import entity.Email;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class PEmails extends javax.swing.JPanel {

    /**
     * Creates new form PPhoneNumbers
     */
    public PEmails() {
        initComponents();
        TEmails.getTableHeader().setReorderingAllowed(false);
        TEmails.getColumn("Email").setPreferredWidth(400);
        TEmails.getColumn("Envío de Resultados").setPreferredWidth(110);
        TEmails.getColumn("Comunicación y Solicitud Certificados").setPreferredWidth(190);
        addTableSelectionListener();
    }
    
    private void addTableSelectionListener() {
        TEmails.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (TEmails.getSelectedRow() != -1)
                    BRemove.setEnabled(true);
                else
                    BRemove.setEnabled(false);
            }
        });
    }
    
    public ArrayList getEmails() {
        ArrayList emails = new ArrayList();
        DefaultTableModel model = (DefaultTableModel) TEmails.getModel();
        
        for (int row = 0; row < model.getRowCount(); row++) {
            String email = (String) model.getValueAt(row, 0);
            if (email != null && email.length() != 0) {
                Email currentEmail = new Email();
                currentEmail.setEmail(email);
                StringBuilder stringBuilder = new StringBuilder();
                for (int col = 1; col < model.getColumnCount(); col++) {
                    if ((boolean) model.getValueAt(row, col))
                        stringBuilder.append("1");
                    else
                        stringBuilder.append("0");
                }
                currentEmail.setType(stringBuilder.toString());
                emails.add(currentEmail);
            }
        }
        return emails;
    }
    
    public void setEmails(List emails) {
        BAdd.setVisible(false);
        BRemove.setVisible(false);
        TEmails.setEnabled(false);
        
        DefaultTableModel model = (DefaultTableModel) TEmails.getModel();
        model.setRowCount(0);
        
        if (emails != null) {
            for (Iterator it = emails.iterator(); it.hasNext();) {
                Email email = (Email) it.next();
                String type = email.getType();
                model.addRow(new Object[]{email.getEmail(),
                            type.substring(0, 1).equals("1"),
                            type.substring(1, 2).equals("1")});
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LTitle = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TEmails = new javax.swing.JTable();
        BAdd = new javax.swing.JButton();
        BRemove = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());

        LTitle.setText("Emails:");

        TEmails.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null,  new Boolean(false),  new Boolean(false)}
            },
            new String [] {
                "Email", "Envío de Resultados", "Comunicación y Solicitud Certificados"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        TEmails.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(TEmails);

        BAdd.setText("Agregar");
        BAdd.setToolTipText("Agregar un campo para Email");
        BAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAddActionPerformed(evt);
            }
        });

        BRemove.setText("Eliminar");
        BRemove.setToolTipText("Eliminar el campo seleccionado");
        BRemove.setEnabled(false);
        BRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LTitle)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BRemove)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(LTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BRemove)
                    .addComponent(BAdd)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAddActionPerformed
        DefaultTableModel model = (DefaultTableModel) TEmails.getModel();
        model.addRow(new Object[] {"",false,false});
    }//GEN-LAST:event_BAddActionPerformed

    private void BRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRemoveActionPerformed
        DefaultTableModel model = (DefaultTableModel) TEmails.getModel();
        int selectedRow = TEmails.getSelectedRow();
        model.removeRow(selectedRow);
        
        if (selectedRow == 0)
            if (TEmails.getRowCount() == 0)
                TEmails.getSelectionModel().setSelectionInterval(-1, -1);
            else
                TEmails.getSelectionModel().setSelectionInterval(0, 0);
        else
            TEmails.getSelectionModel().setSelectionInterval(selectedRow - 1, selectedRow - 1);
    }//GEN-LAST:event_BRemoveActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAdd;
    private javax.swing.JButton BRemove;
    private javax.swing.JLabel LTitle;
    private javax.swing.JTable TEmails;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
